<!DOCTYPE html>
<html lang="en">

<head>
	<base href="$$.RootPath$$">
	<title>Login - Shiori</title>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<link rel="apple-touch-icon-precomposed" sizes="152x152" href="assets/res/apple-touch-icon-152x152.png">
	<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/res/apple-touch-icon-144x144.png">
	<link rel="icon" type="image/png" href="assets/res/favicon-32x32.png" sizes="32x32">
	<link rel="icon" type="image/png" href="assets/res/favicon-16x16.png" sizes="16x16">
	<link rel="icon" type="image/x-icon" href="assets/res/favicon.ico">

	<link href="assets/css/source-sans-pro.min.css" rel="stylesheet">
	<link href="assets/css/fontawesome.min.css" rel="stylesheet">
	<link href="assets/css/stylesheet.css" rel="stylesheet">

	<script src="assets/js/vue.min.js"></script>
	<script src="assets/js/url.min.js"></script>
</head>

<body>
	<div id="login-scene" :class="{night: nightMode}">
		<p class="error-message" v-if="error !== ''">{{error}}</p>
		<div id="login-box">
			<form @submit.prevent="login">
				<div id="logo-area">
					<p id="logo">
						<span>栞</span>shiori
					</p>
					<p id="tagline">simple bookmark manager</p>
				</div>
				<div id="input-area">
					<label for="username">Username: </label>
					<input id="username" type="text" name="username" placeholder="Username" tabindex="1" autofocus />
					<label for="password">Password: </label>
					<input id="password" type="password" name="password" placeholder="Password" tabindex="2"
						@keyup.enter="login">
					<label class="checkbox-field"><input type="checkbox" name="remember" v-model="remember"
							tabindex="3">Remember me</label>
				</div>
				<div id="button-area">
					<a v-if="loading">
						<i class="fas fa-fw fa-spinner fa-spin"></i>
					</a>
					<a v-else class="button" tabindex="4" @click="login" @keyup.enter="login">Log In</a>
				</div>
			</form>
		</div>
		<div>
			<p>$$.Version$$</p>
		</div>
	</div>

	<script type="module">
		var app = new Vue({
			el: "#login-scene",
			data: {
				error: "",
				loading: false,
				username: "",
				password: "",
				remember: false,
				nightMode: false,
			},
			methods: {
				async getErrorMessage(err) {
					switch (err.constructor) {
						case Error:
							return err.message;
						case Response:
							var text = await err.text();

							// Handle new error messages
							if (text[0] == "{") {
								var json = JSON.parse(text);
								return json.message;
							}
							return `${text} (${err.status})`;
						default:
							return err;
					}
				},
				login() {
					function parseJWT(token) {
						try {
							return JSON.parse(atob(token.split('.')[1]));
						} catch (e) {
							return null;
						}
					}

					// needed to work around autofill issue
					// https://github.com/facebook/react/issues/1159#issuecomment-506584346
					this.username = document.querySelector('#username').value;
					this.password = document.querySelector('#password').value;
					// Validate input
					if (this.username === "") {
						this.error = "Username must not empty";
						return;
					}

					// Remove old cookie
					document.cookie = `session-id=; Path=${new URL(document.baseURI).pathname}; Expires=Thu, 01 Jan 1970 00:00:00 GMT;`;

					// Send request
					this.loading = true;

					fetch(new URL("api/v1/auth/login", document.baseURI), {
						method: "post",
						body: JSON.stringify({
							username: this.username,
							password: this.password,
							remember_me: this.remember == 1 ? true : false,
						}),
						headers: { "Content-Type": "application/json" },
					}).then(response => {
						if (!response.ok) throw response;
						return response.json();
					}).then(json => {
						// Save session id
						document.cookie = `session-id=${json.message.session}; Path=${new URL(document.baseURI).pathname}; Expires=${json.message.expires}`;

						// Save account data
						localStorage.setItem("shiori-token", JSON.stringify(json.message.token));
						localStorage.setItem("shiori-account", JSON.stringify(parseJWT(json.message.token).account));

						// Go to destination page
						var currentUrl = new Url(),
							dstUrl = currentUrl.query.dst,
							dstPage = currentUrl.hash || "home";

						if (dstPage !== "home" && dstPage !== "setting") {
							dstPage = "";
						}

						// TODO: Improve this redirect logic
						var newUrl = new Url(dstUrl || document.baseURI);
						newUrl.hash = dstPage;

						location.href = newUrl;
					}).catch(err => {
						this.loading = false;
						this.getErrorMessage(err).then(msg => {
							this.error = msg;
						})
					});
				},
				loadSetting() {
					var opts = JSON.parse(localStorage.getItem("shiori-setting")) || {},
						nightMode = (typeof opts.nightMode === "boolean") ? opts.nightMode : false;

					this.nightMode = nightMode;
				}
			},
			mounted() {
				// Load setting
				this.loadSetting();
				localStorage.removeItem("shiori-account");
				localStorage.removeItem("shiori-token");

				// <input autofocus> wasn't working all the time, so I'm putting this here as a fallback
				document.querySelector('#username').focus()
			}
		})
	</script>
</body>

</html>
